﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Reflection;
using log4net;
using UsageTracker.Reporting.Data;
using UsageTracker.Reporting;

namespace UsageTracker.Reporting.Pages
{
    public partial class ProdUsageMap : System.Web.UI.Page
    {
        private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 
        /// </summary>
        protected string UsageDistributionChartPath { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected string LocationDistributionChartPath { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Messages.Text = String.Empty;
            GetAllProducts();
        }

        
        /// <summary>
        /// 
        /// </summary>
        private void GetAllProducts()
        {
            if (!Page.IsPostBack)
            {
                log.Info("Getting all products with usage data in the database");
                UsageDataAccess DAL = new UsageDataAccess();
                List<string> collections = DAL.GetAllProductNames();
                log.Info("Retrieved " + collections.Count + " products from the database");

                //Remove the internal Mongodb databases from this list
                if (collections.Contains("startup_log")) collections.Remove("startup_log");
                if (collections.Contains("system.indexes")) collections.Remove("system.indexes");

                this.Products.DataSource = collections;
                
                this.Products.DataBind();
                GetAllHostsForProduct(this.Products.Items[0].Value);
            }
            else
            {
                
            }
        }

        private void GetAllHostsForProduct(string productName)
        {
            log.Info("Getting all hosts for product " + productName + " with usage data in the database");
            
            UsageDataAccess DAL = new UsageDataAccess();
            List<List<string>> hostDetails = DAL.GetAllHostsForProduct(productName, DateTime.MinValue, DateTime.MaxValue);
            log.Info("Retrieved " + hostDetails.Count + " hosts for " + productName + " from the database");
            this.HostNames.Items.Clear();
            if (hostDetails.Count == 0)
            {
                this.HostNames.Items.Add("-- NO HOSTS FOUND --");
            }
            else
            {
                this.HostNames.Items.Add("ALL");
            }

            hostDetails.ForEach(
                h =>
                {
                    this.HostNames.Items.Add(h[4]);
                    
                });
            this.HostNames.DataBind();
            
        }
        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Submit_Click(object sender, EventArgs e)
        {
            UsageDataAccess DAL = new UsageDataAccess();
            string tempPathCharts = ConfigurationManager.AppSettings.Get("CHARTS_TEMP_DIR");
            DAL.ChartingFolderPath = Server.MapPath(tempPathCharts);
            try
            {
                DateTime start = DateTime.Parse(this.StartDate.Text).ToUniversalTime();
                DateTime end = DateTime.Parse(this.EndDate.Text).ToUniversalTime();
                string chartPath = DAL.GetProductUsageDistribution(this.Products.SelectedValue, start, end, (this.HostNames.SelectedValue == "ALL") ? null : this.HostNames.SelectedValue);
                this.UsageDistributionChartPath = "<img id=\"chart1\" src=\"" + tempPathCharts + "/" + chartPath + "\" />";

                string installDistribChartPath = DAL.GetProductInstallationDistribution(this.Products.SelectedValue, start, end);
                this.LocationDistributionChartPath = "<img id=\"chart2\" src=\"" + tempPathCharts + "/" + installDistribChartPath + "\" />";
            }
            catch (Exception exp)
            {
                this.Messages.Text = "Could not generate the usage distribution graph due to an error. Please check the start and end dates entered.";
                log.Error("Could not generate the usage distribution graph due to an error. Details - " + exp.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Products_SelectedIndexChanged(object sender, EventArgs e)
        {
            string prodName = this.Products.SelectedValue;
            log.Info("User selected the product - " + prodName);
            GetAllHostsForProduct(prodName);
        }
    }
}